﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Framework.Extensions
{
    public static class EnumerableExtensions
    {
        public static IEnumerable Cast(this IEnumerable source, Type targetType)
        {
            return (IEnumerable) typeof (Enumerable)
                                     .GetMethod("Cast")
                                     .MakeGenericMethod(targetType)
                                     .Invoke(null, new[] {source});
        }

        public static IEnumerable ToListOfType(this IEnumerable source, Type targetType)
        {
            return (IEnumerable) typeof (Enumerable)
                                     .GetMethod("ToList")
                                     .MakeGenericMethod(targetType)
                                     .Invoke(null, new[] {source.Cast(targetType)});
        }

        public static T Minimum<T>(this IEnumerable<T> elements, Func<T, double> selector)
        {
            var ret = default(T);
            var minValue = double.MaxValue;
            foreach (var element in elements)
            {
                var currentValue = selector(element);
                if (currentValue >= minValue) continue;

                minValue = currentValue;
                ret = element;
            }

            return ret;
        }
    }
}